#!/bin/bash

# === 配置区 ===
PASSWORD="Sunny1234"
REMOTE_USER="appadmin"
REMOTE_HOST="115.159.214.105"
REMOTE_DIR="/home/appadmin/app/web"
NGINX_PORT=13000

# === 1. 本地打包 ===
echo "[1/5] 开始前端项目打包..."
npm install && npm run build
if [ $? -ne 0 ]; then
  echo "前端打包失败，终止部署。"
  exit 1
fi

# === 2. 打包静态资源为 zip ===
cd build || { echo "build 目录不存在"; exit 1; }
ZIP_FILE="code-knowledge-web-$(date +%Y%m%d%H%M%S).zip"
zip -r "$ZIP_FILE" ./*
cd ..

# === 3. 上传 zip 包到服务器 ===
echo -n "[2/5] 正在上传前端zip包..."
(
  sshpass -p "$PASSWORD" scp "build/$ZIP_FILE" "$REMOTE_USER@$REMOTE_HOST:$REMOTE_DIR/" &
  SCP_PID=$!
  while kill -0 $SCP_PID 2>/dev/null; do
    echo -n "."
    sleep 1
  done
  wait $SCP_PID
)
if [ $? -ne 0 ]; then
  echo "\n上传zip包失败"
  exit 1
fi
echo " 完成"

# === 4. 远程解压并替换静态资源 ===
sshpass -p "$PASSWORD" ssh "$REMOTE_USER@$REMOTE_HOST" << EOF
cd $REMOTE_DIR
rm -rf static/  # 清理旧静态资源
unzip -o "$ZIP_FILE"
rm -f "$ZIP_FILE"
EOF

echo "[3/5] 前端全量部署完成！"
